// src/components/AuthRoute.jsx
import { useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { checkTokenValid } from '../utils/auth';
import { message } from 'antd';

const AuthRoute = ({ children, requiresAuth = false }) => {
    const navigate = useNavigate();
    const location = useLocation();
    useEffect(() => {
        const verifyAuth = async () => {
            // 需要权限的路由才校验
            if (requiresAuth) {
                const isValid = await checkTokenValid();
                console.log('isValid', isValid)
                if (!isValid) {
                    message.destroy()
                    message.warning('已退出登录，请重新登录', 2)
                    setTimeout(() => {
                        // // 记录来源路径（包含 search 和 hash）
                        const redirectPath = location.pathname + location.search + location.hash;
                        navigate(`/login?redirect=${encodeURIComponent(redirectPath)}`, {
                            replace: true // 替换历史记录
                        });
                    }, 2000)
                }
            }
        };

        verifyAuth();
    }, [navigate, location, requiresAuth]);

    return children;
};

export default AuthRoute;